/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package au.edu.unsw.bookmarket.dao.impl;

import au.edu.unsw.bookmarket.actionform.SellerBean;
import au.edu.unsw.bookmarket.dao.SellerDao;
import au.edu.unsw.bookmarket.jdo.Seller;
import au.edu.unsw.bookmarket.service.PMF;
import au.edu.unsw.bookmarket.util.BeanMapping;
import java.util.ArrayList;
import java.util.List;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;

/**
 *
 * @author gongz
 */
public class SellerDaoImpl implements SellerDao {

    public void addSellerAsSellerBean(SellerBean sellerBean) {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        BeanMapping beanMapping = new BeanMapping();
        try {
            Seller seller = beanMapping.sellerBean2Seller(sellerBean);
            pm.makePersistent(seller);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            pm.close();
        }
    }

    public void addSeller(Seller seller) {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
            pm.makePersistent(seller);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            pm.close();
        }
    }

    public List<SellerBean> getAllSellers() {
        List<SellerBean> sellerBeans = new ArrayList<SellerBean>();
        BeanMapping beanMapping = new BeanMapping();
        PersistenceManager pm = PMF.get().getPersistenceManager();
        Query query = pm.newQuery(Seller.class);
        try {
            List<Seller> sellers = (List<Seller>) query.execute();
            for (Seller seller : sellers) {
                sellerBeans.add(beanMapping.seller2SellerBean(seller));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            query.closeAll();
        }
        return sellerBeans;
    }

    public boolean removeAllSellers() {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        Query query = pm.newQuery(Seller.class);
        boolean success = false;
        try {
            query.deletePersistentAll();
            success = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            query.closeAll();
        }
        return success;
    }
}
